const BehaviorAll = require("../../../behaviors/behavior_all.js");
const Pay_wx = require("../../../utils/pay_wx.js");
const Tool = require("../../../utils/tool.js");
const ServiceUser = require("../../../service/service_user.js");
const ServiceSys = require("../../../service/service_sys.js");

Component({
  /**
   * behaviors
   */
  behaviors: [BehaviorAll],
  /**
   * 页面的初始数据
   */
  data: {
    /**
     * 支付方式：
     *  微信支付 == 1
     *  线下支付 == 2
     */
    payWay: 1,
    /**
     * 充值金额
     */
    rechargeValue: 1,
    rechargeMinAmount: 0,
    /**
     * 用户全部积分
     */
    score: 0
  },

  methods: {
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      const _this = this;
      // 获取积分
      ServiceUser.getScore(function (data) {
        _this.setData({
          score: data.score
        })
      });
      ServiceSys.get(function (data) {
        _this.setData({
          rechargeMinAmount: data.rechargeMinAmount
        });
      });
    },
    /**
     * 充值金额改变
     */
    onRechargeValueChange: function (e) {
      const _this = this;
      _this.setData({
        rechargeValue: e.detail.value
      });
    },

    /**
     * 切换支付
     */
    onPayWayChange: function (e) {
      const _this = this;
      _this.setData({
        payWay: e.detail.value
      });
      console.log(e.detail.value)
    },

    /**
     * 微信支付
     */
    onPay: function (e) {
      const _this = this;
      const amount = _this.data.rechargeValue;
      //
      if (Number(_this.data.payWay) === 1) {
        _this._payWithWx(amount);
      } else {
        _this._payWithCard(amount);
      }
    },

    /**
     * 微信支付
     */
    _payWithWx: function (amount) {
      // 发起预支付请求
      ServiceUser.createRechargeOrder(amount, function (data) {
        Pay_wx.wxRequestPayment(
          data,
          function (res) {
            wx.navigateTo({ url: '../integral/integral' })
          }
        );
      })
    },

    /**
     * 线下支付
     */
    _payWithCard: function (amount) {
      const _this = this;
      // 验证
      const rechargeMinAmount = _this.data.rechargeMinAmount;
      const rechargeValue = _this.data.rechargeValue;
      if (rechargeValue < rechargeMinAmount) {
        Tool.showInfo("线下充值最小金额为" + rechargeMinAmount + "元");
        return;
      }
      // 提交
      ServiceUser.submitRechargeOrder(amount, function (data) {
        wx.navigateTo({ url: '../integral/integral' })
      });
    }
  }
  
})